import type { QueryRequest, QueryResponse, Skill } from '../types';

export class SidecarClient {
  constructor(private baseUrl: string) {}

  // Query agent with streaming
  async *queryStream(request: QueryRequest): AsyncGenerator<QueryResponse> {
    const response = await fetch(`${this.baseUrl}/api/agent/query/streaming`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(request),
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const reader = response.body?.getReader();
    if (!reader) {
      throw new Error('No response body');
    }

    const decoder = new TextDecoder();
    let buffer = '';

    while (true) {
      const { done, value } = await reader.read();
      if (done) break;

      buffer += decoder.decode(value, { stream: true });
      const lines = buffer.split('\n');
      buffer = lines.pop() || '';

      for (const line of lines) {
        if (line.startsWith('data: ')) {
          const data = line.slice(6);
          if (data === '[DONE]') {
            return;
          }
          try {
            yield JSON.parse(data) as QueryResponse;
          } catch (e) {
            console.error('Failed to parse SSE data:', e);
          }
        }
      }
    }
  }

  // Query agent (single response)
  async query(request: QueryRequest): Promise<string> {
    const response = await fetch(`${this.baseUrl}/api/agent/query`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(request),
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const data = await response.json();
    return data.response;
  }

  // Get all skills
  async getSkills(): Promise<Skill[]> {
    const response = await fetch(`${this.baseUrl}/api/skills`);
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    return response.json();
  }

  // Get active skills
  async getActiveSkills(): Promise<Skill[]> {
    const response = await fetch(`${this.baseUrl}/api/skills/active`);
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    return response.json();
  }

  // Activate skill
  async activateSkill(id: string): Promise<boolean> {
    const response = await fetch(`${this.baseUrl}/api/skills/${id}/activate`, {
      method: 'POST',
    });
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const data = await response.json();
    return data.success;
  }

  // Deactivate skill
  async deactivateSkill(id: string): Promise<boolean> {
    const response = await fetch(`${this.baseUrl}/api/skills/${id}/deactivate`, {
      method: 'POST',
    });
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const data = await response.json();
    return data.success;
  }

  // Health check
  async health(): Promise<{ status: string; version: string }> {
    const response = await fetch(`${this.baseUrl}/health`);
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    return response.json();
  }
}

